<?php

namespace app\api\controller\customer;

use app\api\controller\Api;
use app\common\customer\model\CustomerAllocate;
use app\common\customer\model\CustomerContact;
use app\common\customer\model\UploadBom;
use app\common\customer\model\UploadFile;
use util\Format;

class Upload extends Api
{
    // 上传的文件列表
    public function index()
    {

        $user = $this->request->user;
        $post = $this->request->post();
        $where = [];
        // city_id,source_id,range
        if (isset($post['city_id']) && $post['city_id'] > 0) $where[] = ['city_id', '=', $post['city_id']];
        if (isset($post['source_id']) && $post['source_id'] > 0) $where[] = ['source_id', '=', $post['source_id']];
        // assign_status
        if (isset($post['assign_status']) && $post['assign_status'] !== '') $where[] = ['assign_status', '=', $post['assign_status']];
        if (!empty($post['range'])) {
            $range = Format::dateRange($post['range']);
            $where[] = ['create_time', 'between', $range];
        }

        list($cfg) = Format::pagination($post);
        $model = new UploadFile();
        $where[] = ['user_id', '=', $user['id']];
        $pg = $model->where($where)->order('id desc')->paginate($cfg);
        $listData = $pg->getCollection();
        foreach ($listData as $key => $value) {
            $value->append(['user', 'source', 'city']);
        }

        $result['list'] = $listData;
        $result['pagination'] = Format::pgResult($pg);
        return success($result, '获取数据成功');
    }

    public function create()
    {
        $post = $this->request->post();
        $validate = new \app\common\customer\validate\UploadFileValidate();

        if (!$validate->check($post)) return error([], $validate->getError());

        $user = $this->request->user;
        $post['user_id'] = $user['id'];

        $model = new UploadFile();
        // 查看hash是否存在
//        $hash = $post['hash'];
//        $row = $model->where('hash', $hash)->find();
//        if ($row) return error([], '文件已存在');

        $saveRs = $model->save($post);
        if ($saveRs) {
            return success($model, '上传成功');
        } else {
            return error([], '上传失败');
        }
    }

    // 校验
    public function check()
    {
        $post = $this->request->post();
        if (empty($post['id'])) return error([], '请选择要校验的文件');

        $model = new UploadFile();
        $row = $model->find($post['id']);
        if (empty($row)) return error([], '文件不存在');

        // UploadBom 中是否存在数据 upload_id = $post['id']
        $bomModel = new UploadBom();
        $count = $bomModel->where('upload_id', $post['id'])->count();
        if ($count > 0) return error([], '文件已校验');

        $filePath = '.' . $row->dir_path;
        if (!file_exists($filePath)) return error([], '文件不存在');

        // 读取文件
        $file = fopen($filePath, 'r');
        // 获取总行数
        $total = 0;
        $effective = 0;
        $invalid = 0;
        $contactModel = new \app\common\customer\model\CustomerContact();
        $time = time();
        $data = [
            'upload_id' => $row->id,
            'operator_id' => $row->user_id,
            'city_id' => $row->city_id,
            'source_id' => $row->source_id,
            'create_time' => $time,
            'update_time' => $time,
        ];

        $customerModel = new \app\common\customer\model\Customer();
        while (!feof($file)) {
            $line = fgets($file);
            // 校验
            $line = trim($line);
            if (empty($line)) continue;
            $data['contact'] = $line;
            $contact = $contactModel->where('contact', $line)->find();
            if ($contact) {
                $invalid++;
                $data['is_valid'] = 0;
                // 获取客资的渠道
                $member = $customerModel->where('id', $contact['member_id'])->find();
                $member->append(['source']);
                $data['repetitive'] = $member['source']['title'];
            } else {
                $effective++;
                $data['is_valid'] = 1;
            }
            UploadBom::create($data);
            $total++;
        }
        fclose($file);

        $data = [
            'total' => $total,
            'effective' => $effective,
            'invalid' => $invalid,
        ];
        // 更新row
        $row->save($data);

        return success([], '校验成功');
    }

    public function allocate()
    {
        $post = $this->request->post();
        $user = $this->request->user;
        if (empty($post['file_id'])) return error([], '请选择要分配的文件');
        // user_id
        if (empty($post['user_id'])) return error([], '请选择要分配的员工');

        // 检测是否已经分配
        $model = new UploadFile();
        $file = $model->find($post['file_id']);
        if ($file->assign_status == 1) return error([], '文件已分配');

        $model = new UploadBom();
        $where = [
            ['upload_id', '=', $post['file_id']],
            ['is_valid', '=', 1]
        ];

        $rows = $model->where($where)->count();
        if ($rows == 0) return error([], '没有有效的数据可分配');

        // 按100条进行分页处理
        $total = $rows;
        $limit = 100;
        $pages = ceil($total / $limit);
        $now = time();

        $memberModel = new \app\common\customer\model\Customer();
        for ($i = 0; $i < $pages; $i++) {
            $offset = $i * $limit;
            $list = $model->where($where)->limit($offset, $limit)->select();

            $arr = [];
            foreach ($list as $key => $row) {
                $data = [
                    'member_no' => $memberModel->createMemberNo(),
                    'upload_id' => $row->upload_id,
                    'mobile' => $row->contact,
                    'operator_id' => 1,
                    'city_id' => $row->city_id,
                    'source_id' => $row->source_id,
                    'create_time' => $now,
                    'update_time' => $now,
                ];
                array_push($arr, $data);
            }
            $memberModel->insertAll($arr);
        }

        // $memberModel 分页查询 100 upload_id = $post['file_id'] 进行分配
        $allocateModel = new CustomerAllocate();
        $contactModel = new CustomerContact();
        for ($i = 0; $i < $pages; $i++) {
            $offset = $i * $limit;
            $where = [
                ['upload_id', '=', $post['file_id']],
            ];
            $list = $memberModel->where($where)->limit($offset, $limit)->select();
            $allocate = [];
            $contacts = [];
            foreach ($list as $key => $row) {
                // 构建分配数据
                $data = [
                    'member_no' => $row->member_no,
                    'member_id' => $row->id,
                    'from_user_id' => $user['id'],
                    'create_id' => $row['operator_id'],
                    'user_id' => $post['user_id'],
                    'create_time' => $now,
                    'update_time' => $now,
                ];
                array_push($allocate, $data);

                // 构建联系方式
                $contact = [
                    'member_id' => $row->id,
                    'role' => 9,
                    'type' => 1,
                    'name' => '',
                    'contact' => $row->mobile,
                    'create_time' => $now,
                    'update_time' => $now,
                ];
                array_push($contacts, $contact);
            }
            $allocateModel->insertAll($allocate);
            $contactModel->insertAll($contacts);
        }

        // 对已分配的数据进行标记
        $uploadModel = new UploadFile();
        $uploadModel->where('id', $post['file_id'])->update(['assign_status' => 1]);

        return success([], '数据处理中...');
    }


    // 导出无效客资
    public function export()
    {
        $post = $this->request->post();
        if (empty($post['file_id'])) return error([], '请选择要导出的文件');

        $model = new UploadFile();
        $file = $model->find($post['file_id']);
        if (empty($file)) return error([], '文件不存在');

        $isValid = $post['is_valid'] ?? 0;

        $where = [
            ['upload_id', '=', $post['file_id']],
            ['is_valid', '=', $isValid]
        ];
        $bomModel = new UploadBom();
        // 分页读取数据
        $total = $bomModel->where($where)->count();
        $limit = 100;
        $pages = ceil($total / $limit);

        // 创建文件
        $path = '/uploads/export/' . date('Ymd') . '/' . $file->id .'['.$isValid. '].csv';
        $dir = '.' . dirname($path);
        if (!is_dir($dir)) mkdir($dir, 0777, true);
        $file = fopen('.' . $path, 'w');

        // 读取
        for ($i = 0; $i < $pages; $i++) {
            $offset = $i * $limit;
            $data = $bomModel->where($where)->limit($offset, $limit)->column('contact');
            // 蒋数据写入文件，一条一行
            foreach ($data as $key => $value) {
                fputcsv($file, [$value]);
            }
        }
        fclose($file);

        // 组合url地址
        $path = request()->domain() . $path;

        return success(['path' => $path], '导出成功');
    }
}